package com.dexter.year2023.charpter7_tree_and_recurison.level3;

import com.dexter.year2023.charpter6_tree_level_travel.level1.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 非递归的中序遍历
 *
 * @author Dexter
 */
public class InOrderTraversal {
    public static void main(String[] args) {
        TreeNode node = new TreeNode(3);
        node.left = new TreeNode(9);
        node.right = new TreeNode(20);
        node.right.left = new TreeNode(15);
        node.right.right = new TreeNode(7);
        System.out.println(inOrderTraversal(node));
    }

    public static List<Integer> inOrderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        // 每次访问的节点入栈
        Stack<TreeNode> stack = new Stack<>();
        // 从root开始遍历
        TreeNode node = root;
        while (!stack.isEmpty() || node != null) {
            while (node != null) {
                // 左
                stack.push(node);
                node = node.left;
            }
            // 中
            node = stack.pop();
            res.add(node.val);
            // 右
            node = node.right;
        }
        return res;
    }
}
